<template>
  <div>
    <!-- 头部搜索 start -->
    <el-form ref="queryForm"
      class="query-form"
      :model="queryParams"
      size="small"
      :inline="true"
      >
      <el-form-item label="状态"
        prop="status">
        <el-select v-model="queryParams.status"
          @change="handleQuery">
          <el-option key="all"
            label="全部"
            :value="10"/>
          <el-option
            label="已上架"
            :value="1" />
          <el-option
            label="待上架"
            :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item class="big-query" label="关键词"
        prop="keyword">
        <el-input v-model="queryParams.keyword"
          placeholder="输入权益包ID，权益包名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
          @clear="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
          @click="handleQuery">搜索</el-button>
        <el-button size="small"
          @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 头部搜索 end -->

    <!-- 头部操作栏 start -->
    <el-button type="primary"
      icon="el-icon-plus"
      style="margin-bottom:10px"
      size="small"
      @click="handleAdd">新增</el-button>
    <!-- 头部操作栏 end -->

    <!-- 表格数据 start  -->
    <el-table v-loading="loading"
      :data="rightPackageList">
      <el-table-column label="权益包标识ID"
        width="110"
        prop="pkg_id" />
      <el-table-column label="权益包名称"
        min-width="120"
        prop="name" />
      <el-table-column label="权益包图标"
        width="150"
        prop="icon">
        <template slot-scope="scope">
          <el-image slot="reference"
            style="height: 36px;cursor: pointer;"
            :src="scope.row.icon"
            fit="fill"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="权益包权重"
        width="120"
        sortable
        prop="weight" />
      <el-table-column label="权益包描述"
        min-width="160"
        show-overflow-tooltip
        prop="describe" />
      <el-table-column label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" disable-transitions>{{ scope.row.status === 1 ? '已上架' : '待上架' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作"
        width="160"
        fixed="right"
        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small " type="text" @click="handleSale(scope.row)" :disabled="scope.row.status !== 0">上架</el-button>
          <el-button size="small"
            type="text"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="small"
            type="text"
            :disabled="scope.row.status !== 0"
            @click="handleDelete(scope.row)">删除</el-button>
          <!-- <el-button size="small" type="text">查看数据统计</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList" />
    <!-- 表格数据 end -->

    <!-- 添加或修改对话框 start -->
    <el-dialog :title="form.id?'修改权益包':'新增权益包'"
      :visible.sync="open"
      width="800px"
      top="10vh"
      :close-on-click-modal="false"
      @closed="reset">
      <el-form ref="form"
        :model="form"
        :rules="rules"
        label-width="110px">
        <el-form-item
          label="所属项目"
          prop="appids">
          <select-check-box v-model="form.appids"
            :selOptions="permission_projectList"
            :props="{value: 'app_id', label: 'name'}"
            style="width:100%">
          </select-check-box>
        </el-form-item>
        <el-form-item label="权益包标识ID"
          prop="pkg_id">
          <el-input v-model="form.pkg_id"
            placeholder="请输入权益包标识ID"
            :disabled="!!form.id"/>
        </el-form-item>
        <el-form-item label="权益包名称"
          prop="name">
          <el-input v-model="form.name" placeholder="请输入权益包名称"/>
        </el-form-item>
        <el-form-item label="最低版本" prop="min_ver">
          <el-input v-model.trim="form.min_ver"/>
        </el-form-item>
        <el-form-item label="权益包描述" prop="describe">
          <el-input v-model="form.describe" placeholder="请输入权益包描述"/>
        </el-form-item>
        <el-form-item label="权益包权重" prop="weight">
          <el-input-number v-model="form.weight"
            :min="0" :precision="0"></el-input-number>
        </el-form-item>
        <el-form-item label="权益配置" :inline="false">
        </el-form-item>
        <el-form-item label-width="20px">
          <el-row v-for="(item,index) in form.right_cats" :key="item.cat_id" flex :gutter="10" style="margin-bottom:22px">
            <el-col :span="6">
              <el-form-item :prop="'right_cats.'+index+'.cat_id'" :rules="{required: true, message: '分类不能为空', trigger: 'blur'}">
                <el-select v-model="item.cat_id" style="width:100%" placeholder="请选择分类">
                  <el-option v-for="itemb in classList"
                    :key="itemb.cat_id"
                    :label="itemb.name"
                    :value="itemb.cat_id"
                    :disabled="disabledChoose(itemb,index)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item :prop="'right_cats.'+index+'.right_id'" :rules="{required: true, message: '权益不能为空', trigger: 'blur'}">
                <el-select
                  multiple
                  filterable
                  v-model="item.right_id"
                  @keydown.native.delete.capture.stop.prevent
                  style="width:100%"
                  placeholder="请选择权益">
                  <el-option v-for="itemc in rightsOptions"
                    :key="itemc.id"
                    :label="itemc.right_id+'  '+itemc.name"
                    :value="itemc.id"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button type="text" icon="el-icon-bottom" v-if="index!==form.right_cats.length-1" @click="swapItems(index,1)"></el-button>
              <el-button type="text" icon="el-icon-top" v-show="index!==0" @click="swapItems(index,-1)"></el-button>
              <el-button type="text" icon="el-icon-circle-plus-outline" v-show="index===form.right_cats.length-1&&form.right_cats.length<20" @click="addClass"></el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="权益包图标" prop="icon">
          <ImgUpload v-model="form.icon"/>
        </el-form-item>
      </el-form>
      <div slot="footer"
        class="dialog-footer">
        <el-button type="primary" v-if="form.id" @click="submitForm(0)">确认</el-button>
      <el-button type="primary" v-if="!form.id" @click="submitForm(0)">新增</el-button>
      <el-button type="primary" v-if="!form.id" @click="submitForm(1)">新增并上架</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改对话框 end -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import ImgUpload from '@/components/img-upload'
import { classList } from '@/api/rights/class'
import { listRightPackage, addRightPackage, getPackageId, updateRightPackage, delRightPackage, updateStatus } from '@/api/rights/package'
import { listRights } from '@/api/rights/rights'
export default {
  name: 'RightsPackage',
  components: {
    ImgUpload
  },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 等级表格数据
      rightPackageList: [],
      // 权益选项
      rightsOptions: [],
      classList: [],
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        id: null,
        appids: [],
        min_ver: '',
        pkg_id: '',
        name: '',
        describe: '',
        weight: 0,
        right_cats: [],
        icon: ''
      },
      packageIdList: [], // 可选权益包类型
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        status: 10,
        keyword: undefined
      },
      // 表单校验
      rules: {
        right_cats: [
          { required: true, message: '权益包分类不能为空', trigger: 'blur' }
        ],
        appids: [
          { required: true, type: 'array', message: '所属项目不能为空', trigger: 'blur' }
        ],
        pkg_id: [
          { required: true, message: '权益包标识ID不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '权益包名称不能为空', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '请上传图标', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList']),
    disabledChoose () {
      return function (item, index) {
        let findItemIndex = this.form.right_cats.findIndex(item2 => item2.cat_id === item.cat_id)
        return findItemIndex !== -1 && index !== findItemIndex
      }
    }
  },
  activated () {
    classList({ page: 1, page_size: 100 }).then(res => {
      this.classList = res.data.list || []
    })
  },
  created () {
    this.getList()
    classList({ page: 1, page_size: 100 }).then(res => {
      this.classList = res.data.list || []
    })
    getPackageId({
      dictType: 'right_package_cats',
      pageSize: 200,
      pageIndex: 1
    }).then(res => {
      this.packageIdList = res.data.list || []
    })
  },
  methods: {
    /** 查询权益类别列表 */
    getList () {
      this.loading = true
      listRightPackage(this.queryParams).then(response => {
        this.rightPackageList = response.data.list
        this.total = response.data.count || 0
      }).finally(() => {
        this.loading = false
      })
    },
    /** 表单重置  */
    reset () {
      this.resetForm('form')
      this.form.id = null
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd () {
      listRights({ page: 1, page_size: 500, status: 1 }).then(respense => {
        this.rightsOptions = respense.data.list
      })
      this.form.right_cats = [{
        cat_id: null,
        right_id: []
      }]
      this.open = true
    },
    /** 修改按钮操作 */
    async handleUpdate (row) {
      let right_cats = []
      let selcted_rightids = []
      if (row.cat_list && row.cat_list.length) {
        right_cats = row.cat_list.map(item => {
          return {
            cat_id: item.cat_id,
            right_id: this.getAttrs(item.right_list, 'id')
          }
        })
      } else {
        right_cats = [{
          cat_id: null,
          right_id: []
        }]
      }
      for (const item of right_cats) {
        selcted_rightids = selcted_rightids.concat(item.right_id)
      }
      await listRights({ page: 1, page_size: 500, status: 1 }).then(respense => {
        let list = respense.data.list
        this.rightsOptions = list
      })
      this.open = true
      this.$nextTick(() => {
        const keys = Object.keys(this.form)
        for (const item of keys) {
          this.form[item] = row[item]
        }
        this.form.right_cats = right_cats
        this.form.id = row.package_id
      })
    },
    swapItems (index, step) {
      const index2 = index + step
      const arr = this.form.right_cats
      arr[index] = arr.splice(index2, 1, arr[index])[0]
    },
    /** 上架按钮操作 -待做 */
    handleSale (row) {
      this.$confirm('是否确认上架该权益包？权益包名：' + row.name, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateStatus(row.package_id).then(() => {
          this.getList()
          this.msgSuccess('操作成功')
        })
      })
    },
    /** 提交按钮 */
    submitForm: function (status) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateRightPackage(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            this.form.status = status
            addRightPackage(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const packageId = row.package_id
      const { pageIndex, pageSize } = this.queryParams
      this.$confirm(`是否确认删除该权益包？权益包名：${row.name}`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRightPackage(packageId).then(() => {
          this.queryParams.pageIndex = this.getCurrentPage({ total: this.total, pageSize, pageIndex })
          this.getList()
          this.msgSuccess('删除成功')
        })
      })
    },
    addClass () {
      this.form.right_cats.push({
        cat_id: null,
        right_id: []
      })
    }
  }
}
</script>
<style lang="scss">
.none {
  display: none !important;
}
.el-table .el-image {
  /deep/.el-image__inner {
    max-height: 36px;
  }
}
</style>
